<!doctype html>
<body>
  <script src=/resources/testharness.js></script>
  <script src=/resources/testharnessreport.js></script>
  <script src=/permissions-policy/resources/permissions-policy.js></script>
  <script src=/common/utils.js></script>
  <script src=/fenced-frame/resources/utils.js></script>
  <script src=/shared-storage/resources/util.js></script>
  <script>
    'use strict';
    const header = 'permissions policy header shared-storage=(self)';

    const rawSetHeader = 'set;key=hello;value=world';
    const setHeader = encodeURIComponent(rawSetHeader);
    const sameOriginFetchUrl =
      `/shared-storage/resources/shared-storage-write.py?write=${setHeader}`;
    const sameOriginImageUrl =
      `/shared-storage/resources/shared-storage-writable-pixel-write.png`
      + `?write=${setHeader}`;
    const sameOriginIframeUrl =
      `/shared-storage/resources/shared-storage-write-notify-parent.py`
      + `?write=${setHeader}`;
    const sameOrigin = generateURL(sameOriginFetchUrl, []).origin;
    const crossOrigin = 'https://{{domains[www]}}:{{ports[https][0]}}';

    promise_test(async t => {
      let redirectURL = crossOrigin
        + '/shared-storage/resources/cors-redirect.py?location='
        + sameOrigin + sameOriginFetchUrl;
      let response = await fetch('/shared-storage/resources/cors-redirect.py'
                                 + '?location=' + encodeURIComponent(redirectURL),
                                 {sharedStorageWritable: true});
      let sharedStorageWritableHeader = await response.text();
      assert_equals(sharedStorageWritableHeader, "?1");

      await verifyKeyValueForOrigin('hello', 'world', sameOrigin);
      await deleteKeyForOrigin('hello', sameOrigin);
    }, header + ' allows the \'Shared-Storage-Writable\' header to be sent '
       + 'for the redirect of a shared storage fetch request, '
       + 'where the redirect has a same-origin URL, even if an '
       + 'intermediate redirect has a cross-origin URL.');

    promise_test(async t => {
      let redirectURL = crossOrigin
        + '/shared-storage/resources/cors-redirect.py?location='
        + sameOrigin + sameOriginImageUrl;
      let image = document.createElement('img');
      image.src = '/shared-storage/resources/cors-redirect.py?location='
                  + encodeURIComponent(redirectURL);
      image.sharedStorageWritable = true;

      const promise = new Promise((resolve, reject) => {
        image.addEventListener('load', () => {
          resolve(image);
        });
        image.addEventListener('error', () => {
          reject(new Error('Image load failed'));
        });
      });
      document.body.appendChild(image);

      await promise;

      await verifyKeyValueForOrigin('hello', 'world', sameOrigin);
      await deleteKeyForOrigin('hello', sameOrigin);
    }, header + ' allows the \'Shared-Storage-Writable\' header to be sent '
       + 'for the redirect of a shared storage image request, '
       + 'where the redirect has a same-origin URL, even if an '
       + 'intermediate redirect has a cross-origin URL.');

    promise_test(async t => {
      let redirectURL = crossOrigin
        + '/shared-storage/resources/cors-redirect.py?location='
        + sameOrigin + sameOriginIframeUrl;
      let frame = document.createElement('iframe');
      frame.src = '/shared-storage/resources/cors-redirect.py?location='
                  + encodeURIComponent(redirectURL);
      frame.sharedStorageWritable = true;

      const promise = new Promise((resolve, reject) => {
        window.addEventListener('message', async function handler(evt) {
          if (evt.source === frame.contentWindow) {
            assert_equals(evt.data.sharedStorageWritableHeader, '?1');
            document.body.removeChild(frame);
            window.removeEventListener('message', handler);
            resolve();
          }
        });
        window.addEventListener('error', () => {
          reject(new Error('Navigation error'));
        });
      });
      document.body.appendChild(frame);

      await promise;

      await verifyKeyValueForOrigin('hello', 'world', sameOrigin);
      await deleteKeyForOrigin('hello', sameOrigin);
    }, header + ' allows the \'Shared-Storage-Writable\' header to be sent '
       + 'for the redirect of a shared storage iframe request, '
       + 'where the redirect has a same-origin URL, even if an '
       + 'intermediate redirect has a cross-origin URL.');
  </script>
</body>
